package com.digitalchina.lxnsy.activity.management;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.PlantVO;
import com.digitalchina.lxnsy.entity.SeedVO;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity.management
 * 创建人：郑皓
 * 创建时间：2019/4/23 20:21
 * 修改备注：
 * ================================================
 */
public class AddPlantActivity extends BaseActivity {

    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.et_area)
    EditText etArea;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.tv_variety)
    TextView tvVariety;

    private PlantVO vo;
    private OptionsPickerView pvName, pvVariety;
    private String PlantInfoID = "";
    private String cropId = "";// 农作物ID
    private String varietyId = ""; // 品种ID

    private List<SeedVO> voList = new ArrayList<>();
    private List<SeedVO> varietyList = new ArrayList<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_add_plant);
        setTitle("添加种植");
    }

    @Override
    public void initMember() {

        getSeedList();

        vo = (PlantVO) getIntent().getSerializableExtra("PlantVO");
        if (vo != null && vo.getIndex() > -1) {
            tvType.setText(vo.getCropName());
            etArea.setText(vo.getPlantArea());
            etNum.setText(vo.getOrderNum());
            PlantInfoID = vo.getPlantInfoId();
            cropId = vo.getCropId();
            varietyId = vo.getVarietyId();
            tvVariety.setText(vo.getVarietyName());
        }


    }

    @Override
    public void addListener() {
    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0: // 保存
                        String id = FastJsonUtil.getString(message.obj.toString(), "plantInfoId");
                        Intent i = new Intent();
                        vo.setCropName(tvType.getText().toString());
                        vo.setPlantArea(etArea.getText().toString());
                        vo.setOrderNum(etNum.getText().toString());
                        vo.setVarietyName(tvVariety.getText().toString());
                        vo.setPlantInfoId(id);
                        i.putExtra("PlantVO", vo);
                        setResult(RESULT_OK, i);
                        CustomDialog.nativeDialogFinish(activity, "保存成功");
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_1:
                        callBack(message.obj);
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void callBack(Object object) {

        voList = FastJsonUtil.getListBean(object.toString(), "list", SeedVO.class);
        varietyList = new ArrayList<>();

        pvName = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (voList == null || voList.size() == 0) {
                    showToast("正在获取作物，请稍候重试");
                    return;
                }

                tvType.setText(voList.get(options1).getPickerViewText());
                cropId = voList.get(options1).getId();

                tvVariety.setText("");
                varietyId = "";
                varietyList.clear();
                for (int i = 0; i < voList.get(options1).getVariety().size(); i++) {
                    varietyList.add(voList.get(options1).getVariety().get(i));
                }
                pvVariety.setPicker(varietyList);
            }
        })
                .setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("作物")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.7f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.app_color))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0, 0)  //设置默认选中项
                .build();

        pvName.setPicker(voList);


        pvVariety = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                tvVariety.setText(varietyList.get(options1).getPickerViewText());
                varietyId = varietyList.get(options1).getId();
            }
        })
                .setTitleText("品种")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvVariety.setPicker(varietyList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_type, R.id.bt_save, R.id.layout_variety})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.layout_type:
                if (pvName != null) {
                    pvName.show();
                } else {
                    showToast("正在获取作物列表");
                }
                break;
            case R.id.layout_variety:
                if (pvVariety != null) {
                    if (StringUtil.isTextEmpty(tvType) || varietyList.size() <= 0) {
                        showToast("请先选择作物");
                    } else
                        pvVariety.show();
                } else {
                    showToast("正在获取品种");
                }
                break;
            case R.id.bt_save:

                if (StringUtil.isStrEmpty(tvType.getText().toString())) {
                    showToast("请选择作物");
                    return;
                }
                if (StringUtil.isStrEmpty(tvVariety.getText().toString())) {
                    showToast("请选择品种");
                    return;
                }
                if (StringUtil.isEditEmpty(etArea)) {
                    showToast("请填写种植面积");
                    return;
                }

                if (StringUtil.isEditEmpty(etNum)) {
                    showToast("请填写订单量");
                    return;
                }

                addPlant();
                break;
        }
    }

    private void addPlant() {

        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("PlantInfoID", PlantInfoID);
        params.put("cropId", cropId);
        params.put("varietyId", varietyId);
        params.put("plantarea", etArea.getText().toString());
        params.put("ordernumber", etNum.getText().toString());

        OkHttpUtil.post(activity, URL.URL_SAVE_PLANT, "正在保存", params, mHandler,
                MSG_S_0, MSG_F_0);
    }


    // 获取农作物品种
    private void getSeedList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("type", "1");

        OkHttpUtil.post(activity, URL.URL_GET_SEED_LIST, "", params, mHandler,
                MSG_S_1, MSG_F_1);
    }
}
